import {ref,reactive,onMounted } from 'vue'
import { appWindow,WebviewWindow,LogicalSize } from '@tauri-apps/api/window'

// 监听并记录窗口坐标
export function windowPosition(){
    onMounted(()=>{
        const unlisten = appWindow.listen('tauri://move',async (event:any)=>{
            let strwin = localStorage.getItem(appWindow.label);
            if(strwin){
                let win = JSON.parse(strwin);
                const factor = await appWindow.scaleFactor();
                win.position.x = event.payload.x/factor;
                win.position.y = event.payload.y/factor;
                localStorage.setItem(appWindow.label,JSON.stringify(win));
            }
        })
    })
}


// 禁止文本选择
export function forbidSelect(dom:any = document){
    onMounted(()=>{
        dom.addEventListener("selectstart", function (e:any) {
            e.preventDefault();
        });
    })
}

//初始化窗口
export function initWindow(){
    let str = localStorage.getItem('wins')
    if(str){
        let wins = JSON.parse(str);
        wins.forEach( function(element:string) {
            // 获取窗口信息
            let strwin = localStorage.getItem(element);
            if(strwin){
                let win = JSON.parse(strwin);
                new WebviewWindow(element,{
                    decorations:false,
                    transparent:true,
                    skipTaskbar:true,
                    x:win.position.x,
                    y:win.position.y,
                    width:win.width,
                    height:win.height,
                    maxHeight:win.height,
                    maxWidth:win.width,
                    url:win.url,
                    alwaysOnTop:win.alwaysOnTop,
                    fileDropEnabled:win.fileDropEnabled,
                })
            }
        });
    }
}

// 检查进程列表是否存在相同应用在运行中，如果有则退出程序
import { exit } from '@tauri-apps/api/process';
import { Command } from '@tauri-apps/api/shell';
export const checkRun =  async function (){
    // 新建命令对象
    let command = new Command('tasklist')
    // 命令执行逻辑
    let num = 0;
    command.stdout.on('data', (data:any)=>{
        let n =  data.indexOf("SkyDesk");
        if(n>=0){
            num = num + 1; 
        }
        if(num>=2){
            exit(1);
        }
    });
    // 执行命令
    const child = await command.spawn();
}